<script setup lang='ts' name="personnel-organizational">
import type { VxeGridInstance, VxeGridListeners, VxeTableEvents, VxeTableInstance } from 'vxe-table'
import { deleteOrganization, deleteStaff, exportStaff, getOrganizationByUser, getOrganizationList, getStaffList } from '@fl/api/joint-api'
import ButtonItem from '@fl/components/button-item.vue'
import { ElButton, ElCard, ElTree } from 'element-plus'
import {  Search ,Download} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useMessage } from '@fl/hooks/web/use-message'
import type { IRowV0 } from './types'

import { TextDict, TypeDict } from './constant'
import AddMenu from './component/add-menu.vue'
import resetCodeBox from './component/resetCodeBox.vue'
import EditUserModal from './component/EditUserModal.vue'
import AssignRolesBox from './component/AssignRolesBox.vue'
import { useForm } from './hooks/use-form'
import { useTable } from './hooks/use-table'
import { formatTime } from '@fl/utils'
import { useUserStore } from '@fl/store/modules/user'

type Tree = {
    [key: string]: any
}

const show = ref(false)
const addRef = ref()
const isTrue = ref(true)
const { btns, gridOptions } = useTable()
const { form, schema } = useForm()
const tempPagingStrat = ref(0)
const tempPagingEnd = ref(10)
tempPagingEnd.value = tempPagingStrat.value + 10
const tableRef = ref<VxeTableInstance<IRowV0>>()
const currentOrgId = ref('')
const currentRow = ref({})
const companyId = ref('')
const showaddDialog = ref(false)

const userStore = useUserStore()
const isAdmin = ref<boolean>(userStore.getUserInfo?.userFlag === '1')

const xGrid = ref<VxeGridInstance<IRowV0>>()
const startIdx = ref(0)
const treeData = ref<any>([])

const resetCodeVisible = ref(false)
const assignVisible = ref(false)
const currentUser = ref({
    accountUuid: '',
    userName: '',
    id: '',
})
const editSection = ref(false)
const modalVisible = ref(false)
const editType = ref(false)
const defaultProps = {
    children: 'children',
    label: 'organizationName',
    value: 'id',
}

const treeRef = ref<InstanceType<typeof ElTree>>()
const filterText = ref('')
const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
            startIdx.value = (currentPage - 1) * pageSize
        }
        getUserList()
    },
}

function searchStaff() {
    gridOptions.pagerConfig.currentPage = 1
    getUserList()
}

function formatParams(formValue) {
    let params = { ...formValue }
    if (formValue.createTime?.length) {
        formValue.startTime = formatTime(formValue.createTime[0], 'yyyy-MM-dd HH:mm:ss')
        formValue.endTime = formatTime(formValue.createTime[1], 'yyyy-MM-dd HH:mm:ss')
    }
    else {
        formValue.startTime = ''
        formValue.endTime = ''
    }
    params = {
        ...formValue,
        pageNum: gridOptions.pagerConfig.currentPage,
        pageSize: gridOptions.pagerConfig.pageSize,
        organizationId: currentOrgId.value,
    }
    delete params.createTime

    return params
}

// 右侧人员数据
// 首次+重置：用userId即企业号查；点击树：userId置为空，用deptId查
function getUserList() {
    gridOptions.loading = true
    const data = formatParams(form.value)
    getStaffList(data).then((res) => {
        console.log('data res', res)
        gridOptions.data = res.records
        gridOptions.pagerConfig.total = res.total
        gridOptions.loading = false
    })
}

// 点击机构树
function handleNodeClick(data, tnode) {
    console.log('🚀 ~ handleNodeClick ~ data, tnode:', data, tnode)

    // 递归获取parentId
    // function getParentIdList(node) {
    //     const list = []
    //     function collect(currentNode) {
    //         if (currentNode) {
    //             list.unshift(currentNode.data.id) // 将当前节点 ID 添加到数组开头
    //             if (currentNode.parent) {
    //                 collect(currentNode.parent) // 继续收集父节点
    //             }
    //         }
    //     }

    //     collect(node)
    //     return list
    // }
    // const newArr = getParentIdList(tnode)
    // console.log('🚀 ~ handleNodeClick ~ newArr:', newArr)

    currentRow.value = data
    currentOrgId.value = data.id
    companyId.value = data.companyId
    form.value.companyId = data.companyId
    form.value.userId = ''
    // console.log('点击data', data)
    getUserList()
}

const { isPending, mutateAsync: runGetOrg } = useMutation({
    mutationFn: () => getOrganizationList(),
    mutationKey: ['getOrganizationList'],
    onSuccess: async (res) => {
        treeData.value = res.records
        getUserList()
    },
})

const { isPending: isPendingByUser, mutateAsync: runGetOrgByUser } = useMutation({
    mutationFn: () => getOrganizationByUser(),
    mutationKey: ['getOrganizationByUser'],
    onSuccess: async (res) => {
        // console.log('🚀 ~ onSuccess: ~ res:', res)
        treeData.value = [res]
        currentOrgId.value = res.id
        form.value.organizationId = res.id
        form.value.companyId = res.companyId
        getUserList()
    },
})

function getOrgList() {
    if (isAdmin.value) {
        runGetOrg()
    }
    else {
        // 组织机构树
        runGetOrgByUser()
    }
}

onMounted(() => {
    getOrgList()
})

function reset() {
    form.value = {
        phone: '',
        userName: '',
        createTime: [],
        activeStatus: '',

    }
    getUserList()
}
const { createConfirmModal, createMessage } = useMessage()

function doEditMenu(row: any) {
    console.log('🚀 ~ doEditMenu ~ row:', row.id)

    show.value = true
    editSection.value = true
    currentOrgId.value = row.id
    currentRow.value = row
}

// 删除类目
// const { mutate: mutateMenuDel } = useHelpMenuDel()
function doDelMenu(row: any) {
    if (row?.catalogVOList?.length) {
        createMessage.error('当前存在子目录，禁止删除')
        return
    }
    createConfirmModal({ content: '是否确认删除？', onError: () => {}, onSuccess: () => {
        deleteOrganization(row.id).then((res) => {
            createMessage.success('操作成功')
            getOrgList()
        })
    } })
}

const hoverStates = ref({}) // 存储节点悬停状态，格式：{ [node.id]: boolean }

function handleMouseEnter(node) {
    hoverStates.value = { [node.id]: true }
}
function handleMouseLeave(node) {
    hoverStates.value = { [node.id]: false }
}

// 分配角色
function assignRoles(row: any) {
    assignVisible.value = true
    currentUser.value = row
}

function deleteUser(row) {
    deleteStaff(row.id).then((res) => {
        createMessage.success('操作成功')
        getUserList()
    })
}

function doAction(item: any, row: any) {
    console.log('🚀 ~ doAction ~ item: any, row:', item, row)

    // 编辑人员
    if (item.value === 'edit') {
        currentUser.value = row
        modalVisible.value = true
        editType.value = true
    }
    else if (item.value === 'resetPwd') {
        resetPwd(row)
    }
    else if (item.value === 'assignRoles') {
        assignRoles(row)
    }
    else if (item.value === 'delete') {
        deleteUser(row)
    }
}

// 新增人员
function doAdd() {
    currentUser.value = {}
    modalVisible.value = true
    // editType.value = true
    currentOrgId.value = form.value.id || treeData.value[0]?.id
}

async function doExport() {
    const data = formatParams(form.value)
    const result = await exportStaff({ ...data, pageSize: 1000000 })
    const blob = new Blob([result], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const objectUrl = URL.createObjectURL(blob)
    location.href = objectUrl
    URL.revokeObjectURL(objectUrl)
}

// 重置密码
function resetPwd(row: any) {
    resetCodeVisible.value = true
    currentUser.value = row
}

const selectAllChangeEvent: VxeTableEvents.CheckboxAll<IRowV0> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    }
}

const selectChangeEvent: VxeTableEvents.CheckboxChange<IRowV0> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '勾选事件' : '取消事件', records)
    }
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function filterNode(value: string, data: Tree) {
    if (!value)
        return true
    return data.organizationName?.includes(value)
}

// 部门管理
function createSection() {
    show.value = true
    editSection.value = false
}
</script>

<template>
    <div flex
         justify-between
         bg-white
    >
        <ElCard v-show="!showaddDialog"
                style="width:26%"
                shadow="never"
        >
            <div mb-10
                 
            >
            <ElButton 
                          class="el-button mb-6 w-[100%]"
                          @click="createSection"
                          plain
                >
                  + 新增部门
                </ElButton>

                <ElInput v-model="filterText"
                class="w-[100%]"
                  :suffix-icon="Search"
                clearable
                         placeholder="请输出部门名称查询"
                />

                
            </div>

            <ElTree ref="treeRef"
                    style="max-width: 300px"
                    :data="treeData"
                    :loading="isPending || isPendingByUser"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    :default-expand-all="isTrue"
                    :highlight-current="isTrue"
                    :expand-on-click-node="isTrue"
                    @node-click="handleNodeClick"
            >
                <template #default="{ node, data }">
                    <div class="custom-tree-node flex flex-auto w-[100%] overflow-hidden justify-between"
                         @mouseenter="handleMouseEnter(node)"
                         @mouseleave="handleMouseLeave(node)"
                    >
                        <span class="inline-block w-[70%] overflow-hidden overflow-ellipsis">{{ node.label }}</span>

                        <div v-show="data.parentId != 0 && hoverStates[node.id]">
                            <ElIcon class="mr-4"
                                    @click.stop="doEditMenu(data)"
                            >
                                <EditPen />
                            </ElIcon>
                            <!-- &nbsp; -->
                            <ElIcon @click.stop="doDelMenu(data)">
                                <Delete />
                            </ElIcon>
                        </div>
                    </div>
                </template>
            </ElTree>
        </ElCard>

        <ElCard v-show="!showaddDialog"
                style="width:80%"
                 shadow="never"
        >
            <div class="mb-20 p-20">
                <PlusForm v-model="form"
                          :row-props="{ gutter: 20 }"
                          :columns="schema"
                          class="w-[100%]"
                >
                    <template #footer>
                        <div class="ml-auto">
                            <ElButton type="primary"
                                      @click="searchStaff"
                            >
                                查询
                            </ElButton>

                            <ElButton @click="reset">
                                重置
                            </ElButton>
                        </div>
                    </template>
                </PlusForm>
            </div>

            <div class="p-20 border-t-1 border-gray-200">
                <div class="mb-20 flex justify-between">
                    <ElButton type="primary"
                              @click="doAdd"
                    >
                        +新增人员
                    </ElButton>

                    <ElButton @click="doExport" >
                     <span class="vxe-icon-download mr-4" />
                        导出
                    </ElButton>
                </div>
                <!-- 列表 -->
                <vxe-grid ref="xGrid"
                          v-bind="gridOptions"
                          :seq-config="{ startIndex: startIdx }"
                          v-on="gridEvents"
                          @checkbox-all="selectAllChangeEvent"
                          @checkbox-change="selectChangeEvent"
                >
                    >
                    <template #status="{ row }">
                        <div style="cursor: pointer;">
                            <ElTag :type="TypeDict[row.activeState]">
                                {{ TextDict[row.activeState] }}
                            </ElTag>
                        </div>
                    </template>

                    <template #operate="{ row }">
                        <ButtonItem :btns="btns"
                                    @btn-click="doAction($event, row)"
                        />
                    </template>
                </vxe-grid>
            </div>
        </ElCard>
    </div>

    <AddMenu ref="addRef"
             v-model:show="show"
             v-model:currentRow="currentRow"
             v-model:currentId="currentOrgId"
             v-model:editSection="editSection"
             v-model:treeData="treeData"
             @confirm="getOrgList"
    />

    <EditUserModal v-if="modalVisible"
                   v-model:type="editType"
                   v-model:visible="modalVisible"
                   v-model:user="currentUser"
                   v-model:companyId="companyId"
                   v-model:currentOrgId="currentOrgId"
                   v-model:treeData="treeData"
                   @confirm="getUserList"
    />

    <resetCodeBox v-model:visible="resetCodeVisible"
                  v-model:user="currentUser"
    />

    <AssignRolesBox v-if="assignVisible"
                    v-model:user="currentUser"
                    v-model:visible="assignVisible"
                    @confirm="getUserList"
    />
</template>

<style lang="scss" scoped>
:deep(.el-row) {
    // width: 80%;
}
:deep(.el-button--small) {
    padding: 5px 6px;
}
:deep(.el-button + .el-button) {
    margin-left: 8px;
}
</style>
